package demo;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

class MyStack {
    private Queue<Integer> qu1;
    private Queue<Integer> qu2;
    public MyStack() {
        qu1 = new LinkedList<>();
        qu2 = new LinkedList<>();
    }
    
    public void push(int x) {
        if(!qu1.isEmpty()) {
            qu1.offer(x);
        }else if(!qu2.isEmpty()) {
            qu2.offer(x);
        }else {
            // 如果两个都为空 默认放在第一个
            qu1.offer(x);
        }
    }
    
    public int pop() {
        //如果两个队列都为空
        if(empty()) {
            return -1;
        }
        if(!qu1.isEmpty()) {
            int currentSize = qu1.size();
            for (int i = 0; i < currentSize-1; i++) {
                int x= qu1.poll();
                qu2.offer(x);
            }
            return qu1.poll(); //最后一个数据返回1
        }
        if(!qu2.isEmpty()) {
            int currentSize = qu2.size();
            for (int i = 0; i < currentSize-1; i++) {
                int x= qu2.poll();
                qu1.offer(x);
            }
            return qu2.poll(); //最后一个数据返回1
        }
        return -1;
    }
    
    public int top() {
        //如果两个队列都为空
        if(empty()) {
            return -1;
        }
        if(!qu1.isEmpty()) {
            int currentSize = qu1.size();
            int x = -1;
            for (int i = 0; i < currentSize; i++) {
                x = qu1.poll();
                qu2.offer(x);
            }
            return x; //最后一个数据返回1
        }
        if(!qu2.isEmpty()) {
            int currentSize = qu2.size();
            int x = -1;
            for (int i = 0; i < currentSize; i++) {
                x = qu2.poll();
                qu1.offer(x);
            }
            return x; //最后一个数据返回1
        }
        return -1;
    }
    
    public boolean empty() {
        return qu1.isEmpty() && qu2.isEmpty();
    }

    public static void main(String[] args) {
        Stack<Integer> s = new Stack();
        s.push(1);
        s.push(2);
        s.push(3);
        s.push(4);
        System.out.println(s.size()); // 获取栈中有效元素个数---> 4
        System.out.println(s.peek()); // 获取栈顶元素---> 4
        s.pop(); // 4出栈，栈中剩余1 2 3，栈顶元素为3
        System.out.println(s.pop()); // 3出栈，栈中剩余1 2 栈顶元素为3
        if (s.empty()) {
            System.out.println("栈空");
        } else {
            System.out.println(s.size());
        }
    }

    public static void main1(String[] args) {
        MyStack myStack = new MyStack();
        myStack.push(1);
        myStack.push(2);
        myStack.top();

    }
}